package com.fingerth.demo.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import java.lang.reflect.ParameterizedType
import kotlin.coroutines.CoroutineContext

abstract class BaseFrag<T : ViewBinding> : Fragment(), CoroutineScope {
    private var _binding: T? = null
    val vBinding get() = _binding!!
    private val job: Job by lazy { Job() }

    open fun onView(): View? = null

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job // Activity的协程

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        savedInstanceState?.let { arguments?.putAll(it) }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val v = onView()
        return if (v != null) v else {
            try {
                (javaClass.genericSuperclass as? ParameterizedType)?.let { _binding = (it.actualTypeArguments[0] as Class<*>).getMethod("inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java).invoke(null, inflater, container, false) as T }
            } catch (ex: Exception) {
                ex.printStackTrace()
            }
            if (_binding != null) vBinding.root else View(context)
        }
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initData()
    }


    override fun onSaveInstanceState(outState: Bundle) {
        arguments?.let { outState.putAll(it) }
        super.onSaveInstanceState(outState)
    }

    override fun onDestroy() {
        super.onDestroy()
        job.cancel()
        _binding = null
    }

    abstract fun initData()


}